﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using SoundEdge.Dashboard.Project;
using System.ComponentModel.Composition;
using SoundEdge.Media.Settings;
using System.ComponentModel.Composition.Hosting;

namespace SoundEdge.Dashboard
{
    [Export]
    public partial class frmDesign : DockContent
    {
        public bool Active { get; private set; }

        private SoundEdgeProject _associatedProject;

        [ImportMany(typeof(IOutputDevicePlugin))]
        public IEnumerable<IOutputDevicePlugin> OutputDevicePlugins { get; set; }

        public frmDesign(SoundEdgeProject associatedProject)
        {
            InitializeComponent();
            _associatedProject = associatedProject;
            waveFilterLibrary1.Project = associatedProject;

            var catalog = new AssemblyCatalog(typeof(IOutputDevicePlugin).Assembly);
            CompositionContainer container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            Active = true;
        }

        protected override void OnDeactivate(EventArgs e)
        {
            base.OnDeactivate(e);
            Active = false;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (_associatedProject != null && !_associatedProject._saved)
            {
                if (MessageBox.Show(string.Format("Save project {0} before closing?", _associatedProject.Title), "Save project", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    e.Cancel = !Utils.SaveProject(_associatedProject, _associatedProject._fileName);
                }
            }

            base.OnClosing(e);
        }

        private void frmDesign_Load(object sender, EventArgs e)
        {
            if (Configuration.OutputMediaSettings != null)
            {
                wavePlayer1.OutputPlugin = Configuration.OutputMediaSettings.GetPlugin(OutputDevicePlugins);
            }
        }

        private void wavePlayer1_DeviceStatusChange(object sender, Media.DeviceStatusChangeEventArgs e)
        {
            if (e.State == Media.PlayerState.StreamReady)
            {
                wavePainter1.MainProvider = wavePlayer1.Provider;
            }
        }
    }
}
